/**
 * Created by Tianshaokai on 2014/12/18.
 */
var log4js = require('log4js');
var logger = log4js.getLogger('normal');
var config = require('app-config').config;

var AdminUser = require('../proxy').AdminUser;

/**
 *  登录
 * @param req
 *      userName 用户名
 *      pwd 密码
 *      ip ip地址
 * @param res
 * @param next
 */
exports.login = function(req, callback) {
    if(req.method !== 'POST') {
        return callback(config.returncode.paramswrong);
    }
    var userName = req.body.userName;
    var password = req.body.password;
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    logger.debug('username ' + userName + ' password ' + password);
    var fileds = 'userName password';

    AdminUser.getUserByNameAndPasswd(userName, password, fileds, function(err, result) {
        if( err ) {
            logger.error('login database fail----',err);
            return callback(config.returncode.databaseerr);
        }
        if(result != null && result != undefined) {
            return callback({
                code: config.returncode.right.code,
                message: config.returncode.right.message,
                userId: result._id,
                userName: result.userName
            });
        } else {
            return callback(config.returncode.nameOrPassWrong);
        }
    });
};

/**
 *  注册
 * @param req userName 用户名  pwd 密码
 * @param callback
 * @returns {*}
 */
exports.register = function(req, callback) {
    if(req.method !== 'POST') {
        return callback(config.returncode.paramswrong);
    }
    var userName = req.body.userName;
    var password = req.body.password;
    logger.debug('username  ' + userName + ' password ' + password);
    var filed = 'userName';
    AdminUser.getUserByName(userName, filed, function(err, result) {
        if( err ) {
            logger.error('login database fail----',err);
            return callback(config.returncode.databaseerr);
        }
        if(result != null && result != undefined) {
            logger.debug('result: ' + result.userName);
            return callback(config.returncode.userRegistered);
        }

        AdminUser.register(userName, password, function(err, data) {
            if(err) {
                logger.debug("save userName and password failure " + err);
                return callback(config.returncode.databaseerr);
            }
            return callback({code: 0, message: '注册成功！！'});
        });
    });


};